package com.ruoyi.common.validator;


import com.ruoyi.common.annotation.EffectiveTime;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


public class EffectiveTimeValidator implements ConstraintValidator<EffectiveTime, Long> {
    private boolean required = true;
    private Long diffTime = 60000L;

    /**
     * 用于初始化注解上的值到这个validator
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(EffectiveTime constraintAnnotation) {
        this.required = constraintAnnotation.required();
        this.diffTime = constraintAnnotation.diffTime();
    }

    /**
     * 校验方法， 每个需要校验的请求都会走这个方法
     * 具体的校验逻辑
     * @param value 时间戳
     * @param context
     * @return 校验是否通过
     */
    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        if (required) {
            boolean isOk = Math.abs(System.currentTimeMillis() - value) < diffTime;
            return isOk;
        }
        return false;
    }
}
